import * as common from './common'
import {roomManager} from './room';
import * as _ from 'lodash'
const {ccclass, property} = cc._decorator;
var log=console.log
@ccclass
export default class main extends cc.Component {
    @property(cc.Node)
    signInWindow:cc.Node
    transmitReceive(signInfo,url){
        try{
            var socket = new WebSocket('ws:'+url)
            socket.onopen = e=>{
                socket.send(JSON.stringify(signInfo))
            }
        }catch(e){
            return new Promise((res,rej)=>{
                res(null)
            })
        }
        
        return new Promise((res, rej)=>{
            socket.onmessage = e=>{
                res(JSON.parse(e.data))
            }
        })
    }
    start () {
        this.node.getChildByName('logUsr').on(cc.Node.EventType.TOUCH_END,res=>{
            var uid = this.node.getChildByName('uid').getComponent(cc.EditBox).string
            var roomId = this.node.getChildByName('roomBox').getComponent(cc.EditBox).string
            var ip = this.node.getChildByName('ipBox').getComponent(cc.EditBox).string
            if(uid.length==6 && parseInt(uid).toString().length==6 && roomId.length==6 && parseInt(roomId).toString().length==6){
                this.transmitReceive(
                    {
                        task:'login',data:{ uid }
                    },
                    ip
                ).then(data=>{
                    if(data){
                        common.setUid(uid)
                        common.setRoomId(roomId)
                        common.setUrl('ws:'+ip)
                        cc.director.loadScene("game")
                    }else
                        common.alert("请填写正确信息", this.node)
                })
            }else common.alert("请填写完整信息", this.node)
        })

        this.node.getChildByName('signIn').on(cc.Node.EventType.TOUCH_END,touch=>{
            var ip = this.node.getChildByName('ipBox').getComponent(cc.EditBox).string
            if(ip.length<5) common.alert("请输入服务器地址", this.node)
            else this.signInWindow.active = true
        })

        this.signInWindow.getChildByName('loginConfirm').on(cc.Node.EventType.TOUCH_END, e=>{
            var uid = this.signInWindow.getChildByName('idBox').getComponent(cc.EditBox).string
            var name = this.signInWindow.getChildByName('nameBox').getComponent(cc.EditBox).string
            var ip = this.node.getChildByName('ipBox').getComponent(cc.EditBox).string
            if(uid.length==6 && parseInt(uid).toString().length==6){
                this.transmitReceive(
                    {
                        task:'signIn',data:{ uid, name }
                    },
                    ip
                ).then((data)=>{
                    common.alert("注册成功", this.node)
                    this.node.getChildByName('uid').getComponent(cc.EditBox).string = uid
                })
            }
            this.signInWindow.active = false
        })
    }
}
